<template>
  <div class="order-edit-container">
    <div class="page-header">
      <h2 class="page-title">{{ isEdit ? '编辑订单' : '创建订单' }}</h2>
      <div>
        <el-button @click="goBack">返回</el-button>
        <el-button :loading="submitting" type="primary" @click="submitForm">保存</el-button>
      </div>
    </div>

    <el-card class="form-card">
      <el-form
          ref="formRef"
          :model="orderForm"
          :rules="rules"
          label-position="right"
          label-width="120px"
          status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNumber">
              <el-input v-model="orderForm.orderNumber" disabled placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="orderForm.supplierName" placeholder="请输入供应商名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="orderForm.status" style="width: 100%">
                <el-option label="待收货" value="待收货"></el-option>
                <el-option label="已收货" value="已收货"></el-option>
                <el-option label="已开票" value="已开票"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                  v-model="orderForm.purchaseDate"
                  placeholder="选择采购日期"
                  style="width: 100%"
                  type="date"
                  value-format="YYYY-MM-DD"
                  @change="() => validateDates('purchaseDate')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期望交货日期" prop="expectedDeliveryDate">
              <el-date-picker
                  v-model="orderForm.expectedDeliveryDate"
                  placeholder="选择期望交货日期"
                  style="width: 100%"
                  type="date"
                  value-format="YYYY-MM-DD"
                  @change="() => validateDates('expectedDeliveryDate')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购员" prop="purchaser">
              <el-input v-model="orderForm.purchaser" placeholder="请输入采购员"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input-number v-model="orderForm.totalAmount" :disabled="true" :precision="2"
                           style="width: 220px"></el-input-number>
          <span class="text-gray-500 ml-2">元 (根据商品明细自动计算)</span>
        </el-form-item>

        <el-divider content-position="left">商品信息</el-divider>
        <div class="goods-list-header">
          <el-button type="primary" @click="addGoodsRow">
            <el-icon class="mr-1">
              <Plus/>
            </el-icon>
            添加商品
          </el-button>
        </div>

        <el-table :data="orderForm.items || []" border class="goods-table" style="width: 100%; margin-bottom: 20px">
          <el-table-column align="center" label="序号" type="index" width="60"></el-table-column>

          <el-table-column label="商品名称" min-width="300">
            <template #default="scope">
              <el-form-item :prop="'items.' + scope.$index + '.itemName'" :rules="[
                {required: true, message: '请输入商品名称', trigger: 'blur'}
              ]" class="no-margin">
                <el-input v-model="scope.row.itemName" placeholder="请输入商品名称"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="规格型号" min-width="180">
            <template #default="scope">
              <el-form-item :prop="'items.' + scope.$index + '.specification'" class="no-margin">
                <el-input v-model="scope.row.specification" placeholder="请输入规格型号"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="单位" width="100">
            <template #default="scope">
              <el-form-item :prop="`items.${scope.$index}.unit`" :rules="rules.unit" class="no-margin">
                <el-input v-model="scope.row.unit" placeholder="单位"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="140">
            <template #default="scope">
              <el-form-item :prop="`items.${scope.$index}.quantity`" :rules="rules.quantity" class="no-margin">
                <el-input-number
                    v-model="scope.row.quantity"
                    :min="1"
                    :precision="0"
                    controls-position="right"
                    style="width: 100%"
                    @change="() => calculateRowAmount(scope.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="单价(元)" width="180">
            <template #default="scope">
              <el-form-item :prop="`items.${scope.$index}.unitPrice`" :rules="rules.unitPrice" class="no-margin">
                <el-input-number
                    v-model="scope.row.unitPrice"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    controls-position="right"
                    style="width: 100%"
                    @change="() => calculateRowAmount(scope.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="金额(元)" width="140">
            <template #default="scope">
              <el-input v-model="scope.row.total" class="text-center" disabled/>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="100">
            <template #default="scope">
              <el-button circle plain size="small" type="danger" @click="removeGoodsRow(scope.$index)">
                <el-icon>
                  <Delete/>
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="amount-summary">
          <span class="label">订单总金额：</span>
          <span class="value">{{ formatCurrency(totalAmount) }}</span>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import type {Order, OrderItem} from '@/api/types.ts';
import {createOrder, getOrderDetail, updateOrder} from '@/api/order.ts';
import {Delete, Plus} from '@element-plus/icons-vue';

// 路由
const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const submitting = ref(false);
const loading = ref(false);

// 判断是编辑模式还是创建模式
const isEdit = computed(() => !!route.params.id);
const orderId = computed(() => route.params.id ? Number(route.params.id) : undefined);

// 订单表单，确保items始终是一个数组
const orderForm = reactive<Order>({
  orderNumber: '系统自动生成',
  supplierName: '', // 供应商名称，对应数据库字段supplier_name
  status: '待收货', // 订单状态，对应数据库字段status
  totalAmount: 0, // 总金额，对应数据库字段total_amount
  purchaseDate: new Date().toISOString().split('T')[0], // 采购日期，对应数据库字段purchase_date
  expectedDeliveryDate: '', // 期望交货日期，对应数据库字段expected_delivery_date
  purchaser: '', // 采购员，对应数据库字段purchaser
  items: [createEmptyGoodsRow()] // 确保订单明细项始终存在
});

// 表单验证规则
const rules = reactive<FormRules>({
  purchaseDate: [
    {required: true, message: '请选择采购日期', trigger: 'change'},
    {
      validator: (rule, value, callback) => {
        if (value && orderForm.expectedDeliveryDate && value > orderForm.expectedDeliveryDate) {
          callback(new Error('采购日期不能晚于期望交货日期'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  expectedDeliveryDate: [
    {required: true, message: '请选择期望交货日期', trigger: 'change'},
    {
      validator: (rule, value, callback) => {
        if (value && orderForm.purchaseDate && value < orderForm.purchaseDate) {
          callback(new Error('期望交货日期不能早于采购日期'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  supplierName: [
    {required: true, message: '请输入供应商名称', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择订单状态', trigger: 'change'}
  ],
  itemName: [
    {required: true, message: '请输入商品名称', trigger: 'blur'}
  ],
  unit: [
    {required: true, message: '请输入单位', trigger: 'blur'}
  ],
  quantity: [
    {required: true, message: '请输入数量', trigger: 'blur'}
  ],
  unitPrice: [
    {required: true, message: '请输入单价', trigger: 'blur'}
  ]
});

// 计算总金额
const totalAmount = computed((): number => {
  if (!orderForm.items || orderForm.items.length === 0) {
    return 0;
  }
  return orderForm.items.reduce((sum, item) => {
    const itemTotal = Number(item.total || item.amount || 0);
    return sum + itemTotal;
  }, 0);
});

// 监听总金额变化，自动更新表单中的总金额字段
watch(totalAmount, (newValue) => {
  orderForm.totalAmount = Number(newValue);
});

// 监听日期变化，重新验证依赖字段
const validateDates = (dateField: string) => {
  if (!formRef.value) return;

  // 当采购日期变更时，触发期望交货日期校验
  if (dateField === 'purchaseDate' && orderForm.expectedDeliveryDate) {
    formRef.value.validateField('expectedDeliveryDate');
  }

  // 当期望交货日期变更时，触发采购日期校验
  if (dateField === 'expectedDeliveryDate' && orderForm.purchaseDate) {
    formRef.value.validateField('purchaseDate');
  }
};

// 页面加载
onMounted(() => {
  if (isEdit.value && orderId.value) {
    fetchOrderData(orderId.value.toString());
  }
});

// 获取订单详情
const fetchOrderData = async (id: string) => {
  loading.value = true;
  try {
    const response = await getOrderDetail(id);

    // 填充表单数据
    if (response.data) {
      // 直接赋值可能会导致某些字段丢失，特别是嵌套对象如items中的字段
      const orderData = response.data;

      // 确保items中的所有字段都被正确处理
      if (orderData.items && orderData.items.length > 0) {
        orderData.items = orderData.items.map(item => {
          return {
            ...item,
            // 删除商品编码字段
            // 确保其他必要字段也存在并同步
            itemName: item.itemName || item.productName || '',
            productName: item.productName || item.itemName || '',
            unitPrice: item.unitPrice || item.price || 0,
            price: item.price || item.unitPrice || 0,
            total: item.total || item.amount || 0,
            amount: item.amount || item.total || 0
          };
        });
      }

      // 现在用处理后的数据更新表单
      Object.assign(orderForm, orderData);
    } else {
      ElMessage.error('获取订单详情失败，未返回有效数据');
      router.push('/dashboard/order-list');
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败，请重试');
    router.push('/dashboard/order-list');
  } finally {
    loading.value = false;
  }
};

// 返回列表页
const goBack = () => {
  ElMessageBox.confirm('是否确认放弃当前编辑的内容？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/dashboard/order-list');
  }).catch(() => {
  });
};

// 创建空商品行
function createEmptyGoodsRow(): OrderItem {
  return {
    // 基本信息
    id: undefined, // 数据库ID
    itemName: '', // 商品名称
    unit: '', // 单位
    quantity: 1, // 数量
    unitPrice: 0, // 单价

    // 金额相关
    total: 0, // 小计金额
    amount: 0, // 兼容前端代码

    // 其他信息
    productName: '', // 兼容前端代码
    specification: '', // 规格型号
    price: 0 // 兼容前端代码的单价字段
  };
}

// 添加商品行
const addGoodsRow = () => {
  if (!orderForm.items) {
    orderForm.items = [];
  }

  // 创建新商品行并确保所有必要字段都已初始化
  const newItem = createEmptyGoodsRow();

  // 添加到订单明细中
  orderForm.items.push(newItem);
};

// 删除商品行
const removeGoodsRow = (index: number) => {
  if (!orderForm.items || orderForm.items.length <= 1) {
    ElMessage.warning('至少保留一个商品项');
    return;
  }
  orderForm.items.splice(index, 1);
};

// 计算行金额
const calculateRowAmount = (index: number) => {
  if (!orderForm.items) return;

  const row = orderForm.items[index];
  if (!row) return;

  try {
    // 确保数值有效
    const quantity = Number(row.quantity) || 0;
    const price = Number(row.unitPrice) || Number(row.price) || 0;

    // 计算金额并转换为数值类型
    const amount = quantity * price;

    // 同步更新所有相关字段
    row.amount = amount;
    row.total = amount;

    // 确保字段类型一致性
    row.price = price;
    row.unitPrice = price;

    // 同步itemName和productName
    if (row.productName && !row.itemName) {
      row.itemName = row.productName;
    } else if (row.itemName && !row.productName) {
      row.productName = row.itemName;
    }
  } catch (error) {
    console.error(`计算行${index}金额时出错:`, error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 检查商品列表是否为空
  if (!orderForm.items || orderForm.items.length === 0) {
    ElMessage.warning('请至少添加一个商品');
    return;
  }

  // 重新计算所有行的金额
  orderForm.items.forEach((item, index) => {
    calculateRowAmount(index);
  });

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单验证失败:', fields);
      ElMessage.error('请修正表单中的错误');
      return;
    }

    submitting.value = true;
    try {
      // 构建提交的数据
      const submitData: Order = {...orderForm};

      // 确保所有商品都有完整的字段
      if (submitData.items) {
        submitData.items = submitData.items.map(item => {
          // 确保同步字段
          const unitPrice = Number(item.unitPrice) || Number(item.price) || 0;
          const quantity = Number(item.quantity) || 0;
          const total = unitPrice * quantity;

          return {
            ...item,
            itemName: item.itemName || item.productName || '',
            productName: item.productName || item.itemName || '',
            unitPrice: unitPrice,
            price: unitPrice,
            quantity: quantity,
            total: total,
            amount: total
          };
        });
      }

      // 在实际项目中，这里应该调用API提交数据
      if (isEdit.value && orderId.value) {
        await updateOrder(orderId.value.toString(), submitData);
        ElMessage.success('订单更新成功');
      } else {
        await createOrder(submitData);
        ElMessage.success('订单创建成功');
      }

      router.push('/dashboard/order-list');
    } catch (error) {
      console.error('保存订单失败', error);
      ElMessage.error(`${isEdit.value ? '更新' : '创建'}订单失败，请重试`);
    } finally {
      submitting.value = false;
    }
  });
};

// 格式化货币
const formatCurrency = (value: number) => {
  if (value === undefined || value === null) return '¥ 0.00';
  return `¥ ${value.toFixed(2)}`;
};
</script>

<style scoped>
.order-edit-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.form-card {
  margin-bottom: 20px;
}

.goods-list-header {
  margin-bottom: 15px;
}

.goods-table {
  margin: 20px 0;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 通用表单项样式 */
.no-margin {
  margin-bottom: 0 !important;
}

/* 表格内的表单项样式 */
.table-form-item {
  width: 100%;
}

.table-form-item :deep(.el-form-item__content) {
  margin-bottom: 0 !important;
  margin-left: 0 !important;
}

.table-form-item :deep(.el-form-item__error) {
  position: absolute;
}

/* 美化表格头部 */
:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 金额汇总样式 */
.amount-summary {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  font-size: 16px;
}

.amount-summary .label {
  font-weight: bold;
  margin-right: 10px;
}

.amount-summary .value {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

/* 文本居中样式 */
.text-center :deep(.el-input__inner) {
  text-align: center;
}

/* 关键修复：覆盖表格内form-item的margin-left */
:deep(.el-table .el-form-item__content) {
  margin-left: 0 !important;
}

.mr-1 {
  margin-right: 5px;
}

/* 优化数字输入框样式 */
:deep(.el-input-number .el-input__wrapper) {
  padding-right: 30px !important;
}

:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  z-index: 1 !important;
}

:deep(.el-input-number__increase) {
  right: 1px !important;
}

:deep(.el-input-number__decrease) {
  right: 1px !important;
  top: 50% !important;
}
</style> 